<template>
    <div class="words-item">
        <div class="flex items-center justify-between words-item__title font-bold text-14px">
            <div class="flex">
                主关键词
            </div>
            <el-button v-if="!isAdd" type="primary" size="small" @click="isAdd = !isAdd">
                添加
            </el-button>
        </div>
        <div class="pl-16px pr-16px pt-16px h-350px overflow-hidden words-item__list">
            <el-scrollbar>
                <el-checkbox-group v-model="selectedKeywords" v-if="isAdd">
                    <el-checkbox :value="keyword.label" v-for="(keyword, index) in keywords" :key="index">
                        <div class="flex custom-input active">
                            <el-input v-model="keyword.label" clearable placeholder="请输入关键词" @input="(val) => handleInput(val)"></el-input>
                            <el-button v-if="keyword.label" type="danger" :icon="Delete" @click="(evt) => handleDelete()" class="ml-8px"></el-button>
                        </div>
                    </el-checkbox>
                </el-checkbox-group>
            </el-scrollbar>
        </div>
    </div>
</template>

<script setup lang="ts">
import { checkKeywordApi } from '@/api/b2b'
import { confirmMessageBox } from '@/utils/elMessageBox'
import { CircleCloseFilled,Delete,WarningFilled } from '@element-plus/icons-vue'

const props = defineProps<{
    ruleForm: any;
}>()

const isAdd = ref(false)

const keywords = computed(() => {
    return props.ruleForm.mainWords
})

const selectedKeywords = ref<string[]>([]);

// 监听 frontWords 变化，并提取 value > 0 的 label 到 selectedKeywords
watch(
    () => props.ruleForm.mainWords,
    (newFrontWords) => {
        if(newFrontWords){
            selectedKeywords.value = newFrontWords
            .filter((item: any) => item.value > 0)
            .map((item: any) => item.label);
        }
        
    },
    { immediate: true }
);

// 当 selectedKeywords 变化时，更新 frontWords 的 value
watch(
    () => selectedKeywords.value,
    (newSelected, oldSelected) => {
        const newSet = new Set(newSelected);
        const oldSet = new Set(oldSelected);

        // 找出新增项
        const added = newSelected.filter(label => !oldSet.has(label));
        // 找出减少项
        const removed = oldSelected.filter(label => !newSet.has(label));

        // 更新 frontWords 的 value
        props.ruleForm.mainWords.forEach((item: any) => {
            if (added.includes(item.label)) {
                if(!item.value){
                    item.value = 1
                }
            } else if (removed.includes(item.label)) {
                item.value = 0;
            }
        });
    },
    { deep: true }
);

async function handleInput(value:any){
    props.ruleForm.mainWords = [
        {
            label: value,
            value: 1
        }
    ]

    if (!value || typeof value !== 'string' || !value.trim()) {
        selectedKeywords.value = [];
        return;
    }

    try {
        const res: any = await checkKeywordApi({ Keyword: value });
        if (res && res.code === 200) {
            selectedKeywords.value[0] = value;
        } else {
            selectedKeywords.value[0] = '';
            confirmMessageBox(CircleCloseFilled, '关键词校验失败，请重试');
        }
    } catch (error: any) {
        selectedKeywords.value[0] = '';
    }
}

function handleDelete(){
    confirmMessageBox(WarningFilled, '确定删除主关键词吗？', '','',async() => { 
        props.ruleForm.mainWords = [{
            label: '',
            value: 0
        }]
        isAdd.value = false
    })
}


onMounted(() => {
    if(!props.ruleForm.mainWords.length){
        isAdd.value = false
        props.ruleForm.mainWords = [{
            label: '',
            value: 0
        }]
    }else{
        isAdd.value = true
    }
    
})


</script>

<style lang="scss" scoped>
.custom-input{
    .el-input{
        :deep(.el-input__wrapper){
            box-shadow: none !important;
            transition:all 0.3s;
        }
        &:hover{
            :deep(.el-input__wrapper){
                box-shadow: 0 0 0 1px var(--el-input-border-color,var(--el-border-color)) inset !important;
                transition:all 0.3s;
            }
        }
        
    }
    &.active{
        :deep(.el-input__wrapper){
            box-shadow: 0 0 0 1px var(--el-input-border-color,var(--el-border-color)) inset !important;
        }
    }
}
:deep(.el-checkbox__label){
    width: 90%;
}
:deep(.el-button--danger){
    height: 28px;
    padding-left: 8px;
    padding-right: 8px;
}
</style>